package com.korion.aidldemo.im;

import android.os.Handler;
import android.os.RemoteException;

/**
 * @author chenyinying
 * @date 2020-02-13
 */
public class Server extends IServer.Stub {

    private IClient mClient;
    private IMessageListener mListener;
    private Handler mHandler;

    public Server(IMessageListener listener, Handler handler){
        mListener = listener;
        mHandler = handler;
    }

    @Override
    public void sendMessage(final Message message) throws RemoteException {
        if(mListener != null){
            try {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mListener.onMessageReceivce(message);
                    }
                });
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean registerClient(IClient client) throws RemoteException {
        mClient = client;
        return true;
    }

    @Override
    public boolean unregisterClient(IClient client) throws RemoteException {
        mClient = null;
        return true;
    }

    public boolean send2Client(String message){
        if (mClient != null){
            Message msg = new Message(0, message);
            try {
                mClient.sendMessage(msg);
                return true;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
